package com.zyg.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zyg.dao.UserMapper;
import com.zyg.pojo.Dept;
import com.zyg.pojo.EchartsData;
import com.zyg.pojo.Permission;
import com.zyg.pojo.User;
import com.zyg.service.DeptService;
import com.zyg.service.PermissionService;
import com.zyg.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private DeptService deptService;

    @Autowired
    private PermissionService permissionService;

    @Autowired
    private UserMapper userMapper;

    public IPage<User> listWithDept(IPage<User> page, QueryWrapper<User> queryWrapper) {
        // 查询用户数据
        IPage<User> userPage = baseMapper.selectPage(page, queryWrapper);

        // 获取所有用户的部门ID
        List<Integer> deptIds = userPage.getRecords().stream()
                .map(User::getDeptId)
                .distinct()
                .collect(Collectors.toList());

        // 根据部门ID查询部门信息
        Map<Integer, Dept> deptMap = deptService.listByIds(deptIds).stream()
                .collect(Collectors.toMap(Dept::getId, dept -> dept));

        // 设置用户对象的部门信息
        userPage.getRecords().forEach(user -> {
            if (user.getDeptId() != null && deptMap.containsKey(user.getDeptId())) {
                user.setDept(deptMap.get(user.getDeptId()));
            }
        });

        return userPage;
    }

    @Override
    public List<EchartsData> getDeptIndexData() {
        return userMapper.getDeptIndexData();
    }

    @Override
    public List<Permission> getMenuList() {
        List<Permission> menuList = permissionService.getMenuList();
        return menuList;
    }
    @Override
    public List<Permission> getMenuListByUserId(Integer loginId) {
        List<Permission> menuList = permissionService.getMenuListByUserId(loginId);
        return menuList;
    }
}
